// Created by peter on 2018/3/5.

#include <jni.h>
#include <stdio.h>

// 定义一个加法方法
extern "C"
JNIEXPORT jint JNICALL
Java_com_android_peter_jnidemo_MainActivity_addFromJNI(JNIEnv *env, jobject instance, jint x, jint y) {
    jint total;
    total = x + y;

    return total;
}

// 调用java中static方法的函数
extern "C"
JNIEXPORT void JNICALL
Java_com_android_peter_jnidemo_MainActivity_callJavaStaticMethodFromJNI(JNIEnv *env, jobject instance) {
    // 1、获得实例对应的class类
    jclass clazz = env -> GetObjectClass(instance);
    if(clazz == NULL) {
        printf("get object fail!");
        return;
    }
    // 2、通过class类找到对应的method id
    jmethodID methodId = env -> GetStaticMethodID(clazz,"staticMethodCalledByJni","(Ljava/lang/String;)V");
    if(methodId == NULL) {
        printf("get methodId fail!");
        return;
    }
    // 定义一个string作为参数传递给Java方法
    jstring msg = env -> NewStringUTF("msg send by callJavaStaticMethodFromJNI in my-native-lib.cpp .");
    // 3、静态方法通过class获得对应的method
    env -> CallStaticVoidMethod(clazz,methodId,msg);
}

// 调用java中public方法的函数
extern "C"
JNIEXPORT void JNICALL
Java_com_android_peter_jnidemo_MainActivity_callJavaPublicMethodFromJNI(JNIEnv *env, jobject instance) {
    //1.获得实例对应的class类
    jclass clazz = env -> GetObjectClass(instance);
    if(clazz == NULL) {
        printf("get object fail!");
        return;
    }
    //2.通过class类找到对应的method id
    jmethodID methodId = env -> GetMethodID(clazz,"publicMethodCalledByJni","(Ljava/lang/String;)V");
    if(methodId == NULL) {
        printf("get methodId fail!");
        return;
    }
    // 定义一个string作为参数传递给Java方法
    jstring msg = env -> NewStringUTF("msg send by callJavaPublicMethodFromJNI in my-native-lib.cpp .");
    //3.通过obj获得对应的method
    env -> CallVoidMethod(instance,methodId,msg);
}

// 通过FindClass这种反射的方式调用java中的方法
extern "C"
JNIEXPORT void JNICALL
Java_com_android_peter_jnidemo_MainActivity_callJavaMethodByFindClassFromJNI(JNIEnv *env, jobject instance) {
    //1.通过反射获得父类的class类
    jclass clazz = env -> FindClass("com/android/peter/jnidemo/MainActivity");
    if(clazz == NULL) {
        printf("get object fail!");
        return;
    }
    //2.通过class类找到对应的method id
    jmethodID methodId = env -> GetMethodID(clazz,"publicMethodCalledByJni","(Ljava/lang/String;)V");
    if(methodId == NULL) {
        printf("get methodId fail!");
        return;
    }
    // 定义一个string作为参数传递给Java方法
    jstring msg = env -> NewStringUTF("msg send by callJavaMethodByFindClassFromJNI in my-native-lib.cpp .");
    //3.通过obj获得对应的method
    env -> CallVoidMethod(instance,methodId,msg);
}